package com.maple.ble.reader

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.content.Context
import com.maple.ble.device.BleDevice
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.UUID

class BluetoothReadService(private val context: Context,private val device: BleDevice,private val adapter: BluetoothAdapter,private val connectedCallback: () -> Unit, private val receiveCallback: (byteArray: ByteArray) -> Unit) {
    private var connectedThread: AcceptThread? = null

//    fun writeData(sendData: ByteArray) {
//        connectedThread?.writeData(sendData)
//    }
//
//    fun connected(bluetoothSocket: BluetoothSocket?) {
//        if (connectedThread != null) {
//            connectedThread?.cancel()
//            connectedThread = null
//        }
//        connectedThread = AcceptThread(bluetoothSocket)
//        connectedThread?.start()
//    }

    init {
        connectedThread = AcceptThread(device, adapter)
    }
    @SuppressLint("MissingPermission")
    inner class AcceptThread(private val device: BleDevice, private val adapter: BluetoothAdapter) : Thread() {

        private var inputStream: InputStream? = null
        private var outputStream: OutputStream? = null
//        private var connected = false

        private var tmp: BluetoothServerSocket? = null

        val mname: String = "BluetoothChat"
        val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
        init {
//            connected = bluetoothSocket?.isConnected?:false
            try {
                tmp = adapter.listenUsingRfcommWithServiceRecord(
                    mname,
                    uuid
                )
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        override fun run() {
            super.run()
//            connectedCallback.invoke()
//            val buffer = ByteArray(1024)
//            while (connected) {
//                BleLogger.e("GGQ：connected:${connected}")
//                inputStream?.let {
//                    try {
//                        var length: Int
//                        while (it.read(buffer).also { length = it } != -1) {
//                            val dataByteArray = buffer.copyOf(length)
//                            receiveCallback.invoke(dataByteArray)
//                        }
//                    } catch (e: IOException) {
//                        e.printStackTrace()
//                    }
//                }
//            }


            var socket:BluetoothSocket? = null
            while (true) {

                // 这是一个阻塞调用，只会在成功的连接或异常返回
                socket = tmp?.accept()
                if (socket != null) {
                    synchronized(this@BluetoothReadService) {

                    }
                }
            }
        }

        fun writeData(sendData: ByteArray) {
            try {
                outputStream?.write(sendData)
                outputStream?.flush()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        fun cancel() {
            try {
                inputStream?.close()
                outputStream?.close()
//                bluetoothSocket?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}